import appConfig from "@/utils/appConfig";
import Taro from '@tarojs/taro';
import { createGlobalStore } from 'hox';
import request from '@/utils/request';
import { useRequest } from 'ahooks'
import { useCallback, useMemo } from 'react'
import {defaultAvatar, defaultNickName} from '@/utils'
async function getUserInfo(): Promise<User.Info> {
    return request.get('/api/Common/GetLoginState')
};
export const [ useUserStore, getUserStore] = createGlobalStore(() => {

    const authApi = useRequest<PromiseReturnType<ReturnType<AppConfigType['auth']>>, []>(async () => {
        const auth = appConfig.auth
        const oldToken = Taro.getStorageSync<string>('token')
        if (auth) return await auth(oldToken)
        return false
    }, {
        ready: true,
        onSuccess: accessToken => {
            if (accessToken) {
                Taro.setStorageSync('token', accessToken)
            } else {
                Taro.removeStorageSync('token')
            }
        },
        onError: () => {
        }
    })

    const userInfoApi = useRequest(async () => {
        const userInfo = await getUserInfo()
        userInfo.avatar ??= defaultAvatar
        userInfo.nickName ??= defaultNickName
        userInfo.avatarUrl = userInfo.avatar
        return userInfo
    }, {
        ready: Boolean(authApi.data),
    })

    const clear = useCallback(async () => {
        authApi.mutate(undefined)
        Taro.removeStorageSync('token')
        userInfoApi.mutate(undefined)
    }, [authApi.mutate, userInfoApi.mutate])

    const loginAsync = useCallback(async () => {
        const token = await authApi.runAsync()
        // if (token)  await userInfoApi.runAsync()
        if (token) return userInfoApi.run()
        Taro.navigateTo({ url: `/pages/login/index` })
        // return undefined
    }, [])

    const isMember = useMemo(() => {
        if (!userInfoApi.data) return false
        return userInfoApi.data.memberInfos?.length > 0
    }, [userInfoApi.data])

    return {
        clear,
        token: authApi.data,
        setToken: authApi.mutate,
        reAuth: authApi.refresh,
        reAuthAsync: authApi.refreshAsync,
        userInfo: userInfoApi.data,
        isMember,
        refreshUser: userInfoApi.refresh,
        refreshUserAsync: userInfoApi.refreshAsync,
        loginAsync,
    }
})
